/*
 * @(#)ScheduleExecuteDetail.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */

package com.dcivision.alert.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Timestamp;
import java.util.Date;
import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDataMap;

import com.dcivision.alert.bean.UpdateAlert;
import com.dcivision.calendar.bean.CalendarRecord;
import com.dcivision.calendar.dao.CalendarRecordDAObject;
import com.dcivision.framework.DataSourceFactory;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.notification.EmailDeliveryMessage;
import com.dcivision.framework.notification.NotificationWay;
import com.dcivision.framework.notification.NotificationWayFactory;
/**
  ScheduleExecuteDetail.java

  This class is the ScheduleExecuteDetail

    @author           Scott Tong
    @company          DCIVision Limited
    @creation date    22/08/2003
    @version          $Revision: 1.19.4.2 $
*/

public class ScheduleExecuteDetail implements Job {

  public static final String REVISION = "$Revision: 1.19.4.2 $";

  protected Log log = LogFactory.getLog(this.getClass().getName());

  private String recordTitle = "";
  private String userName = "";
  private String actionType = "";
  private String objectType = "";
  private String objectName = "";
  private String atOrBefore = "";
  private String userID = "";
  private String objectID = "";
  private String logID = "";
  private String reminderType = "";
  private int reminderAmount = 0;
  private String notificationWay = "";
  private String targetSrcTime = null;
  private String alertObjectMessag = "";
  
  String alertEmail = null;
  String alertDescription = null;

  /** Creates a new instance of SchedulerTest */
  public ScheduleExecuteDetail() {

  }

  public void execute(org.quartz.JobExecutionContext context) throws org.quartz.JobExecutionException {
    JobDataMap dataMap = context.getJobDetail().getJobDataMap();

    notificationWay = dataMap.getString("notificationWay");
    alertEmail = dataMap.getString("alertEmail");
    recordTitle = dataMap.getString("recordTitle");
    userName = dataMap.getString("userName");
    userID = dataMap.getString("userID");
    actionType = dataMap.getString("actionType");
    objectType = dataMap.getString("objectType");
    objectID = dataMap.getString("objectID");
    objectName = dataMap.getString("objectName");
    targetSrcTime = dataMap.getString("targetSrcTime");
    atOrBefore = dataMap.getString("atOrBefore");
    logID = dataMap.getString("logID");
    alertObjectMessag = dataMap.getString("alertObjectMessag");

    log.debug("method:" + notificationWay + "; EMail:" + alertEmail + ";  desc:" + alertDescription);
    if (notificationWay.indexOf(UpdateAlert.EMAIL_NOTIFICATION) >= 0) {
      this.notifyByEmail();
    }
    if (notificationWay.indexOf(UpdateAlert.SYSTEM_NOTIFICATION) >= 0) {
      this.notifyBySystem();
    }
    log.debug("My job was trigged---" + context.getJobDetail().getFullName() + " executed.[" + new Date() + "]");
  }

  public void notifyBySystem() {
    //SessionContainer sessionContainer = new SessionContainer();
    Connection conn = null;
    PreparedStatement preStat = null;
    String sqlStat = "";
    Timestamp currTime = Utility.getCurrentTimestamp();
    sqlStat += "UPDATE UPDATE_ALERT_SYSTEM_LOG ";
    if (DataSourceFactory.getDatabaseType() == DataSourceFactory.DB_ORACLE) {
      sqlStat += " SET RECORD_STATUS='A', UPDATE_DATE=TO_DATE('" + TextUtility.formatDate(currTime,"yyyy-MM-dd HH:mm:ss")+"','YYYY-MM-DD HH24:MI:SS') ";
    }else{
      sqlStat += " SET RECORD_STATUS='A', UPDATE_DATE='" + currTime + "'";  
    }
    sqlStat += " WHERE  ID=?  ";
    int updateCnt = 0;
    try {
      conn = DataSourceFactory.getConnection();
      preStat = conn.prepareStatement(sqlStat);
      preStat.setInt(1, new Integer(logID).intValue());
      updateCnt = preStat.executeUpdate();
      conn.commit();
    } catch (Exception e) {
      log.error(e, e);
    } finally {
      try {preStat.close();} catch (Exception ignore) {} finally {preStat = null;}
      try {conn.close();} catch (Exception ignore) {} finally {conn = null;}
    }

  }

  public void notifyByEmail() {

    NotificationWay notifyWay = NotificationWayFactory.getNotificationInstance(NotificationWay.EMAIL_NOTIFICATION_INSTANCE);
    Connection conn = null;
    try {
      StringTokenizer st = new StringTokenizer(alertEmail, " ; ", false);
      String sTmp = null;
      conn = DataSourceFactory.getConnection();//TC EDIT:connection should close after using.
      
      while (st.hasMoreTokens()) {

        try {
          sTmp = st.nextToken();
          EmailDeliveryMessage mesg = new EmailDeliveryMessage();
          StringBuffer content = new StringBuffer();
          
          if(alertObjectMessag.length()!= 0){
            content.append(alertObjectMessag); 
          }else{
            CalendarRecordDAObject calendarRecordDAObject = new CalendarRecordDAObject(conn);
            CalendarRecord calendarRecord = null;
            calendarRecord = (CalendarRecord)calendarRecordDAObject.getByID(Integer.valueOf(objectID));
          	if (!Utility.isEmpty(calendarRecord.getEventType())){
              content = this.emailForCalendarReminderContent(calendarRecord.getEventType());
          	} else {
              content = this.emailForCalendarReminderContent();
          	}
          }  
          //Code Add End
          
          String smtpAdminAddress = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_ADDRESS);
          String smtpAdminName = SystemParameterFactory.getSystemParameter(SystemParameterConstant.SMTP_ADMIN_NAME);
          mesg.setSender(new com.dcivision.framework.bean.GenericAddress(smtpAdminAddress, smtpAdminName, "UTF-8"));
          mesg.addToRecipient(new com.dcivision.framework.bean.GenericAddress(sTmp.trim(), sTmp.trim(), "UTF-8"));
          mesg.setSubject("Schedule Management System Notification");
          mesg.setMailContent(content.toString());

          notifyWay.addDeliveryMessage(mesg);
          notifyWay.send();
        } catch (Exception e) {
          log.error("Bad Email address:" + sTmp + ",Ignored");
        }
      }

    } catch (Exception e) {
      log.error("error in add recipient", e);
    }finally{
      try{conn.close();}catch(Exception dber){}finally{conn=null;}
    }
  }

  public StringBuffer emailForCalendarReminderContent() {
    StringBuffer content = new StringBuffer();
    content.append("Dear " + userName + ",\n\n");
    content.append("Event/Meeting Name:" + recordTitle + "\n");
    content.append("Action Date:" + targetSrcTime + "\n");
    content.append("\n\n");
    content.append("Please be aware for this event's coming.\n\n");
    return content;
  }
  
  //Code Add By Jim.Zhou			2006/06/07		Bug #5638
  public StringBuffer emailForCalendarReminderContent(String eventType) {
    StringBuffer content = new StringBuffer();
    content.append("Dear " + userName + ",\n\n");
    if (CalendarRecord.EVENT_TYPE_CALENDAR_MEETING.equals(eventType)){
      content.append("Meeting Name:" + recordTitle + "\n");
    } else if (CalendarRecord.EVENT_TYPE_CALENDAR_EVENT.equals(eventType)){
      content.append("Event Name:" + recordTitle + "\n");
    } else if (CalendarRecord.EVENT_TYPE_CALENDAR_TODO.equals(eventType)){
      content.append("ToDo Name:" + recordTitle + "\n");
    } else {
      content.append("Event/Meeting Name:" + recordTitle + "\n");
    }
    content.append("Action Date:" + targetSrcTime + "\n");
    content.append("\n\n");
    content.append("Please be aware for this event's coming.\n\n");
    return content;
  }
  //Code Add End
}

